const Service = require('egg').Service

class TagService extends Service {
	constructor(ctx) {
		super(ctx)
	}
	async index(params) {
		let { pageSize = 10, pageNum = 1 } = params
		pageSize = Number(pageSize)
		const offset = (pageNum - 1) * pageSize
		const data = await this.ctx.model.Tag.findAndCountAll({
			limit: pageSize,
			offset,
		})
		return data
	}

	async create(body) {
		const { tagName } = body
		const hasOneSameName = await this.ctx.model.Tag.findOne({
			where: { tagName },
		})

		if (hasOneSameName == null) {
			await this.ctx.model.Tag.create({
				...body,
			})
			return 'success'
		}
		return '存在相同数据'
	}

	async destroy(id) {
		const hasOne = await this.ctx.model.Tag.findOne({
			where: { id },
		})
		if (hasOne) {
			await this.ctx.model.Tag.destroy({
				where: { id },
			})
			return 'success'
		}
		return '不存在该数据'
	}

	async update(id, body) {
		const { tagName } = body
		const hasOne = await this.ctx.model.Tag.findOne({
			where: { id },
		})
		if (hasOne) {
			const hasOneSameName = await this.ctx.model.Tag.findOne({
				where: { tagName },
			})
			if (hasOneSameName == null) {
				await this.ctx.model.Tag.update(
					{ ...body },
					{
						where: { id },
					}
				)
				return 'success'
			}
			return '存在相同数据'
		}
		return '不存在该数据'
	}

	async list() {
		const data = await this.ctx.model.Tag.findAndCountAll()
		return data
	}
}

module.exports = TagService
